package za.co.dylanjaneke.airdownloader.command
{
	import flash.events.SQLEvent;
	
	import mx.controls.Alert;
	
	import za.co.dylanjaneke.airdownloader.controller.data.ConnectionManager;
	import za.co.dylanjaneke.airdownloader.events.LoadSettingsEvent;
	import za.co.dylanjaneke.airdownloader.events.LoadShowsSequenceEvent;
	import za.co.dylanjaneke.airdownloader.events.LoadTrackedShowsEvent;
	import za.co.dylanjaneke.airdownloader.events.LoginEvent;
	import za.co.dylanjaneke.airdownloader.model.ScreenNavigatorPM;
	import za.co.dylanjaneke.airdownloader.model.SettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.StatusPM;
	import za.co.dylanjaneke.airdownloader.model.TrackerSettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.vo.DownloadSiteVO;
	import za.co.dylanjaneke.airdownloader.model.vo.SettingsVO;

	/**
	* Author: Dylan Janeke.
	*/
	[Name("loadSettingsCommand")]
	public class LoadSettingsCommand
	{
		[Inject]
		public var trackerSettingsScreenPM:TrackerSettingsScreenPM;
		
		[Inject]
		public var navigator:ScreenNavigatorPM;
		
		[Inject]
		public var repo:ConnectionManager;
		
		[Inject]
		public var statusPM:StatusPM;
		
		public function LoadSettingsCommand()
		{
			
		}
		
		[Observer]
		public function handleLoadSettings(event:LoadSettingsEvent): void
		{
			statusPM.status= "Loading Settings...";
			repo.execute("SELECT * FROM ad_cfg", handleResult);
		}
		
		protected function handleResult(event:SQLEvent): void
		{
			var settings:SettingsVO= SettingsVO.valueOf(event);
			if(settings==null)
			{
				statusPM.status = "Application not configured.";
				navigator.switchView(ScreenNavigatorPM.SETTINGS);
				Alert.show("Please enter your SideReel.com details to continue.","Welcome to AIRDownloader");
			}
			else
			{
				trackerSettingsScreenPM.vo= settings;

				statusPM.status= "Loading Download Sites...";
				repo.execute("SELECT * FROM ad_dl_site", handleSitesResult);			
			}
		}
		
		
		protected function handleSitesResult(event:SQLEvent): void
		{
			trackerSettingsScreenPM.sites= DownloadSiteVO.valueOf(event);
			
			statusPM.status = "http://code.google.com/p/vicariousdownloader/";
			//GlobalEventDispatcher.raiseEvent(new LoadTrackedShowsEvent());
			GlobalEventDispatcher.raiseEvent(new LoginEvent());
		}
		
	}
}